package org.jackysoft.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.net.Socket;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;

import org.apache.commons.collections.iterators.IteratorEnumeration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Lists;

public class Office2PDF implements Callable<String> {

	static final Log log = LogFactory.getLog(Office2PDF.class);
	static Socket server;

	private String ext;
	private InputStream input;
	private int port;
	private String host;


	/**
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param ext
	 *            扩展名
	 * @param data
	 *            数据
	 * */
	public Office2PDF(String host, int port, String ext,InputStream data) {
		this.host = host;
		this.port = port;
		this.ext = ext;
		this.input = data;		
	}

	@Override
	public String call() throws Exception {
		return sendData();
	}
	
    public String sendData(){
    	UUID uuid = UUID.randomUUID();
		String pdfName = uuid.toString();
		
		List<InputStream> inputs = Lists.newArrayList();
		String s= String.format("{\"%s\":\"%s\",\"data:\":\"", "pdfName",pdfName);
		inputs.add(new ByteArrayInputStream(s.getBytes()));
		inputs.add(input);
		s = String.format("\",\"%s\":\"%s\"}", "ext",ext);
		inputs.add(new ByteArrayInputStream(s.getBytes()));
					
		try(@SuppressWarnings("unchecked")
		BufferedInputStream bis = new BufferedInputStream(new SequenceInputStream(new IteratorEnumeration(inputs.iterator())))) {
			log.info("连接到服务器 :" + host + " 端口: " + port);
			server = new Socket(host, port);
			OutputStream socketOut = server.getOutputStream();				
			
			byte[] buf = new byte[1024];
			int read = 0;
			while ((read = bis.read(buf)) != -1) {
				socketOut.write(EncodeUtils.base64Encode(buf).getBytes(), 0, read);
			}
			socketOut.close();
			server.close();
			log.info("数据传送完毕,连接关闭");
		} catch (IOException e) {
			log.error(e);
		}
		return pdfName;
    }

}
